//
//  PrefixViewController.m
//
//  Created by 周成龙
//

#import "PrefixViewController.h"
#import <AudioToolbox/AudioToolbox.h>

@class PrefixSoundPlayer;
@protocol PrefixSoundPlayerDelegate <NSObject>
@optional;
- (void)soundPlayerDidFinish:(PrefixSoundPlayer *)player;
@end

@interface PrefixSoundPlayer : NSObject
@property(nonatomic, weak)id<PrefixSoundPlayerDelegate> delegate;
- (id)initWithURL:(NSURL *)url;
- (void)playerSound;
@end

void PrefixSoundPlayerComplete(SystemSoundID ssID, void *clientData) {
    PrefixSoundPlayer *player = (__bridge PrefixSoundPlayer *)(clientData);
    if ([player.delegate respondsToSelector:@selector(soundPlayerDidFinish:)]) {
        [player.delegate soundPlayerDidFinish:player];
    }
}
@implementation PrefixSoundPlayer {
    SystemSoundID _systemSoundID;
}

- (id)initWithURL:(NSURL *)url {
    if (self = [super init]) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &_systemSoundID);
    }
    return self;
}

- (void)dealloc {
    AudioServicesDisposeSystemSoundID(_systemSoundID);
}

- (void)playerSound {
    
    AudioServicesAddSystemSoundCompletion(_systemSoundID, NULL, NULL, PrefixSoundPlayerComplete, (__bridge void * _Nullable)(self));
    AudioServicesPlaySystemSound(_systemSoundID);
}

@end

@interface PrefixViewController () <PrefixSoundPlayerDelegate>
{
    PrefixSoundPlayer *player;
}
@end

@implementation PrefixViewController
#pragma mark - LifeCycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"VoiceOriginFile.wav" ofType:nil]];
    player = [[PrefixSoundPlayer alloc] initWithURL:url];
    [player playerSound];
    player.delegate = self;
}

#pragma mark - Private

#pragma mark - Delegate
- (void)soundPlayerDidFinish:(PrefixSoundPlayer *)player {
    NSLog(@"播放完成");
}
#pragma mark - Setter / Getter




@end
